import { resetObject } from '@/libs/tools'
import { filterParams } from '@/utils'

export default {
  data () {
    return {
      // 添加接口
      addService: null,
      // 编辑接口
      updateService: null,
      loading: true,
      submitLoading: false,
      isShow: false,
      // 表单参数
      formData: {},
      ruleValidate: null,
      // 接口必须传的参数键值列表
      interfaceParamsKeyList: []
    }
  },
  computed: {
    // 最终发送接口传的参数
    params () {
      const data = filterParams(this.interfaceParamsKeyList, this.formData)
      const { isAdd } = this.$props
      return {
        ...data,
        ...(isAdd ? {} : { id: this.formData.id }),
        ...this.otherParams
      }
    },
    // 接口补充参数
    otherParams () {
      return {}
    }
  },
  props: ['isAdd'],
  methods: {
    validate () {
      if (!this.ruleValidate) {
        this.beforeValidate()
      } else {
        this.$refs.formValidate && this.$refs.formValidate.validate((valid) => {
          if (valid) {
            this.beforeValidate()
          } else {
            this.resetLoading()
          }
        })
      }
    },
    beforeValidate () {
      this.customValidate().then(() => {
        this.submit()
      }).catch(err => {
        err && err.message && this.$Message.error(err.message)
        this.resetLoading()
      })
    },
    customValidate () {
      return new Promise((resolve) => { resolve() })
    },
    async submit () {
      try {
        this.submitLoading = true
        const { isAdd } = this.$props
        const service = isAdd ? this.addService : this.updateService
        if (!service) {
          throw new Error('未定义请求')
        }
        await service(this.params)
        this.$Message.success(isAdd ? '添加成功' : '修改成功')
        this.resetForm()
        this.$emit('onChange')
        this.submitSuccess && this.submitSuccess()
        this.isShow = false
      } catch (e) {
        console.log(e)
      } finally {
        this.submitLoading = false
        this.resetLoading()
      }
    },
    cancel () {
      this.resetForm()
    },
    showModal () {
      this.isShow = true
    },
    // 编辑表单
    setForm (obj) {
      this.formData = { ...{}, ...this.formData, ...obj }
      this.showModal()
    },
    resetForm () {
      this.formData = resetObject(this.formData)
      this.$refs.formValidate && this.$refs.formValidate.resetFields()
      this.afterResetForm()
    },
    afterResetForm () {},
    // 手动重置弹窗loading状态，否则点击确定会自动关闭弹窗
    resetLoading () {
      this.loading = false
      this.$nextTick(() => {
        this.loading = true
      })
    }
  }
}
